/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DAO;

import Conexao.ConnectionFactory;
import Modelo.Endereco;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Danimar
 */
public class EnderecoDAO {

    private Connection connection;

    public EnderecoDAO() throws SQLException
    {
        this.connection = ConnectionFactory.getConnection();
    }

    public void SalvarEndereco(Endereco endereco) throws SQLException
    {
        String sqlInsert = "insert into TB_Endereco (Rua, Numero, Complemento, Bairro, IdCidade) values (?, ?, ?, ?, ?)";
        try
        {
            PreparedStatement statement = this.connection.prepareStatement(sqlInsert);
            statement.setString(0, endereco.getRua());
            statement.setInt(1, endereco.getNumero());
            statement.setString(2, endereco.getComplemento());
            statement.setString(3, endereco.getBairro());
            statement.setInt(4, endereco.getCidade().getId());

            statement.execute();
        }catch (Exception e){
           throw new SQLException("Não foi possível salvar o endereço. ", e);
        }finally{
            this.connection.close();
        }
    }

    public Endereco BuscarEndereco(int id) throws SQLException
    {
        String sqlInsert = "select * from TB_Endereco where IdEndereco = ?";
        try
        {
            PreparedStatement statement = this.connection.prepareStatement(sqlInsert);
            statement.setInt(0, id);
            ResultSet rs = statement.executeQuery();
            Endereco endereco = new Endereco();
            while (rs.next())
            {
                endereco.setId(rs.getInt("IdEndereco"));
                endereco.setRua(rs.getString("Rua"));
                endereco.setNumero(rs.getInt("Numero"));
                endereco.setComplemento(rs.getString("Complemento"));
                endereco.setBairro("Bairro");
            }
            return endereco;
        }catch (Exception e){
           throw new SQLException("Não foi possível salvar o endereço. ", e);
        }finally{
            this.connection.close();
        }
    }

}
